package com.play.ballen.home.ui.fragment

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.os.Handler
import android.text.TextUtils
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import android.widget.RelativeLayout
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.ViewTarget
import com.bumptech.glide.request.transition.Transition
import com.hjq.toast.ToastUtils
import com.luck.picture.lib.thread.PictureThreadUtils.runOnUiThread
import com.play.ballen.R
import com.play.ballen.config.KVConst
import com.play.ballen.databinding.FragmentPiaoliupingBinding
import com.play.ballen.event.EventCost
import com.play.ballen.home.entity.BottleGetGaoji
import com.play.ballen.home.entity.BottleGetJichu
import com.play.ballen.home.entity.BottleList
import com.play.ballen.home.entity.BottlePutGaoji
import com.play.ballen.home.ui.AddBottleActivity
import com.play.ballen.home.ui.BottleDetailActivity
import com.play.ballen.home.ui.MessageActivity
import com.play.ballen.home.ui.ShaiXuanGetActivity
import com.play.ballen.home.vm.PLPFragmentVM
import com.yuven.appframework.util.MMKVUtil
import com.yuven.appframework.widget.banner.util.BannerUtils.dp2px
import com.yuven.baselib.component.BaseMVVMFragment
import com.yuven.baselib.component.eventbus.Event
import com.yuven.baselib.utils.ViewUtils
import java.util.Timer
import java.util.TimerTask

class PlPFragment : BaseMVVMFragment<PLPFragmentVM, FragmentPiaoliupingBinding>() {


    private var widthPixels = 0
    private val timer = Timer()
    private var currentIndex = 0
    private var bottleDataList: List<BottleList> = mutableListOf()
    private var bottleId= 0

    companion object {
        val TAG: String = PlPFragment::class.java.simpleName
        fun newInstance(): PlPFragment {
            return PlPFragment()
        }
    }

    override fun registerEventBus(): Boolean {
        return true
    }

    override fun handleEvent(event: Event<Any>) {
        super.handleEvent(event)
        when (event.code) {
            EventCost.RENG_BOTTLE_SUCCESS -> {
                reng()//扔一个瓶子
            }
        }
    }

    override fun layoutId(): Int {
        return R.layout.fragment_piaoliuping
    }

    override fun viewModelClass(): Class<PLPFragmentVM> {
        return PLPFragmentVM::class.java
    }


    override fun onResume() {
        super.onResume()
        viewModel.getCanGetNum()
    }

    override fun initObserver() {
        super.initObserver()
        viewModel.bottleDetail.observe(this) {
            BottleDetailActivity.start(mContext,it.id)
            viewModel.getCanGetNum()
        }

        viewModel.bottleData.observe(this) {//捞瓶子之后再获取一次次数
            BottleDetailActivity.start(mContext,it.id)
            viewModel.getCanGetNum()

        }
        viewModel.canGetNum.observe(this) {
            if(it.push>0){
                dataBinding.tvRengNum.text = it.push.toString()
                dataBinding.tvRengNum.visibility=View.VISIBLE
            }else{
                dataBinding.tvRengNum.visibility=View.GONE
            }
            if(it.salvage>0){
                dataBinding.tvLaoNum.text = it.salvage.toString()
                dataBinding.tvLaoNum.visibility=View.VISIBLE
            }else{
                dataBinding.tvLaoNum.visibility=View.GONE
            }

            if(it.my_bottle>0){
                dataBinding.tvMyNum.text = it.my_bottle.toString()
                dataBinding.tvMyNum.visibility=View.VISIBLE
            }else{
                dataBinding.tvMyNum.visibility=View.GONE
            }
        }

        viewModel.bottleListData.observe(this) {
            //个数不为0
            if(it.isNotEmpty()){
                dataBinding.plp.visibility = View.VISIBLE
                dataBinding.message.visibility = View.VISIBLE
                val selectedDataCount = it.size / 5 // 选取总数的1/5的数据
                val selectedIndexes = (0 until it.size).shuffled().take(selectedDataCount)
                bottleDataList = it.mapIndexed { index, item ->
                    if (index in selectedIndexes) {
                        item.copy(showContent = true) // 随机设置showContent为true
                    } else {
                        item
                    }
                }

                // 随机打乱列表顺序，然后选择前trueCount个元素将其showContent字段设置为true
                // 打印结果
                bottleDataList.forEach { println("Bottle ID: ${it.bottle_id}, Content: ${it.content}, Show Content: ${it.showContent}") }
                scheduleAnimation()
                hengxiangyidoong(dataBinding.plp) // Pass the new bottle data
                startAnimator()
                hengxiangyidoong(dataBinding.message) // Pass the new bottle data
            }else{
                ToastUtils.show("水里一个瓶子都没有了")
                dataBinding.plp.visibility = View.GONE
                dataBinding.message.visibility = View.GONE
            }
        }
    }

    private fun scheduleAnimation() {
        timer.scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                val currentBottleData = bottleDataList[currentIndex]
                startAnimatorWithBottleData(currentBottleData)
                currentIndex = (currentIndex + 1) % bottleDataList.size
            }
        }, 0, 10000)
    }

    private fun startAnimatorWithBottleData(bottleData: BottleList) {
        runOnUiThread {
            if(!bottleData.showContent){
                dataBinding.message.visibility = View.GONE
            }else{
                dataBinding.message.visibility = View.VISIBLE
                dataBinding.message.ellipsize = TextUtils.TruncateAt.MARQUEE
                dataBinding.message.isSingleLine = true
                dataBinding.message.marqueeRepeatLimit = -1 // 无限循环
                dataBinding.message.isSelected = true // 启动跑马灯
            }
            bottleId = bottleData.bottle_id
            dataBinding.message.text = bottleData.content
        }
    }


    override fun initView() {
        dataBinding.fakeStatusBar.layoutParams.height = ViewUtils.getStatusHeight()
        dataBinding.flMyBottle.setOnClickListener{
            MessageActivity.start(mContext)
        }
        //捞
        dataBinding.flGet.setOnClickListener{
            if( viewModel.canGetNum.value!!.salvage>0){
                //捞瓶子
                dataBinding.wz.setImageResource(R.drawable.laopingzi)
                dataBinding.wz.setVisibility(View.VISIBLE)
                val animator1 =
                    ObjectAnimator.ofFloat(dataBinding.wz, "rotation", 0f, -20f, 0f, 20f, 0f, -20f, 0f, 20f, 0f)
                animator1.duration = 3000
                animator1.interpolator = LinearInterpolator()
                animator1.start()
                Handler().postDelayed({
                    dataBinding.wz.setImageResource(R.drawable.laodaopingzi)
                    val animator2 = ObjectAnimator.ofFloat(dataBinding.wz, "translationY", 0f, -130f)
                    animator2.duration = 800
                    animator2.interpolator = LinearInterpolator()
                    animator2.start()
                    Handler().postDelayed({
                        dataBinding.wz.setVisibility(View.GONE)
                        //位置还原
                        val animator2 = ObjectAnimator.ofFloat(dataBinding.wz, "translationY", -130f, 0f)
                        animator2.duration = 1
                        animator2.start()

                        val bottlegaoji = BottleGetGaoji(
                            age_min = MMKVUtil.decodeInt(KVConst.LAO_AGE_MIN,false)!!,
                            age_max = MMKVUtil.decodeInt(KVConst.LAO_AGE_MAX,false)!!,
                            height_min = MMKVUtil.decodeInt(KVConst.LAO_HEIGHT_MIN,false)!!,
                            height_max = MMKVUtil.decodeInt(KVConst.LAO_HEIGHT_MAX,false)!!,
                            weight_min =  MMKVUtil.decodeInt(KVConst.LAO_WEIGHT_MIN,false)!!,
                            weight_max = MMKVUtil.decodeInt(KVConst.LAO_WEIGHT_MAX,false)!!,
                            shape = MMKVUtil.decodeInt(KVConst.LAO_SHAPE,false)!!,
                            other = MMKVUtil.decodeInt(KVConst.LAO_OTHER,false)!!,
                            is_block =  MMKVUtil.decodeBoolean(KVConst.LAO_IS_BLOCK, false) == true,
                            city = MMKVUtil.decodeString(KVConst.LAO_CITY, false)?: ""
                        )

                        val map = mutableMapOf<String, Any>()
                        map["is_select"] = MMKVUtil.decodeBoolean(KVConst.LAO_SHAIXUAN, false) == true
                        map["normal_conf"] = MMKVUtil.decodeInt(KVConst.LAO_IM,false)?.let { BottleGetJichu(it) }!!
                        map["vip_conf"] = bottlegaoji

                        viewModel.getBottlesalvage(map)
                    }, 2000)
                }, 3200)
            }else{
                ToastUtils.show("今日次数已用完")
            }
        }

        //扔
        dataBinding.flPut.setOnClickListener{
            if(viewModel.canGetNum!=null){
                if( viewModel.canGetNum.value!!.push>0){
                    AddBottleActivity.start(mContext)
                }else{
                    ToastUtils.show("今日次数已用完")
                }
            }
        }

        dataBinding.waveBezier.startAnimation()
        dataBinding.waveBezier1.startAnimation()
        widthPixels = resources.displayMetrics.widthPixels
        dataBinding.plp.setOnClickListener{
//            BottleDetailActivity.start(mContext,126)
//            viewModel.getBottle("125")
            viewModel.getBottle(bottleId.toString())
//            ToastUtils.show( dataBinding.message.text)
        }
        dataBinding.message.setOnClickListener{
//            viewModel.getBottle("125")
            viewModel.getBottle(bottleId.toString())
        }

        //筛选
        dataBinding.llShaixuan.setOnClickListener{
            ShaiXuanGetActivity.start(mContext)
        }


//        startAnimator()
        val bottlegaoji = BottleGetGaoji(
        age_min = MMKVUtil.decodeInt(KVConst.LAO_AGE_MIN,false)!!,
        age_max = MMKVUtil.decodeInt(KVConst.LAO_AGE_MAX,false)!!,
        height_min = MMKVUtil.decodeInt(KVConst.LAO_HEIGHT_MIN,false)!!,
        height_max = MMKVUtil.decodeInt(KVConst.LAO_HEIGHT_MAX,false)!!,
        weight_min =  MMKVUtil.decodeInt(KVConst.LAO_WEIGHT_MIN,false)!!,
        weight_max = MMKVUtil.decodeInt(KVConst.LAO_WEIGHT_MAX,false)!!,
        shape =MMKVUtil.decodeInt(KVConst.LAO_SHAPE,false)!!,
        other = MMKVUtil.decodeInt(KVConst.LAO_OTHER,false)!!,
        is_block =  MMKVUtil.decodeBoolean(KVConst.IS_BLOCK, false)==true,
        city = MMKVUtil.decodeString(KVConst.LAO_CITY, false) ?: ""

        )

        val map = mutableMapOf<String, Any>()
        map["is_select"] = MMKVUtil.decodeBoolean(KVConst.LAO_SHAIXUAN, false) == true
        map["count"] = 100
        map["normal_conf"] = MMKVUtil.decodeInt(KVConst.LAO_IM,false)?.let { BottleGetJichu(it) }!!
        map["vip_conf"] = bottlegaoji
        //拿瓶子
        viewModel.getCanGetNum()
        viewModel.getbottleWater(map)//获取水里的瓶子的。
    }

    private fun startAnimator() {
        //上下浮动
        val animator2 = ObjectAnimator.ofFloat(dataBinding.plp, "translationY", 0f, 15f, -13f, 0f)
        animator2.repeatCount = ValueAnimator.INFINITE
        animator2.repeatMode = ValueAnimator.RESTART
        animator2.duration = 5000
        animator2.interpolator = LinearInterpolator()
        animator2.start()
        //摇摆角度
        val animator3 = ObjectAnimator.ofFloat(dataBinding.plp, "rotation", -10f,5f, 15f,  25f, 15f,5f, -10f)
        animator3.duration = 6000
        animator3.repeatCount = ValueAnimator.INFINITE
        //        animator3.setRepeatMode(ValueAnimator.REVERSE);
        animator3.interpolator = DecelerateInterpolator()
        animator3.start()
    }


    private fun  reng(){

        val imageView = ImageView(context)
        val layoutParams = RelativeLayout.LayoutParams(
            dp2px(80f),  dp2px(80f)
        )
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL)
        layoutParams.setMargins(0, 0, 0, dp2px(500f))
        imageView.layoutParams = layoutParams
        imageView.setImageResource(R.drawable.new_plp)
        dataBinding.mainlayout.addView(imageView)
        val i = dp2px(360f)
        val animator2 = ObjectAnimator.ofFloat(
            imageView,
            "translationY",
            0f,
            dp2px(380f).toFloat(),
            i.toFloat()
        )
        animator2.duration = 1000
        animator2.interpolator = LinearInterpolator()
        animator2.start()
        Handler().postDelayed({ //从左到右平移
            val animator1 =
                ObjectAnimator.ofFloat(imageView, "translationX", 0f, widthPixels.toFloat())
            animator1.interpolator = LinearInterpolator()
            animator1.duration = 6000
            animator1.start()
            //上下浮动
            val animator2 = ObjectAnimator.ofFloat(
                imageView,
                "translationY",
                i.toFloat(),
                i + 15f,
                i - 13f,
                i.toFloat()
            )
            animator2.duration = 5000
            animator2.interpolator = LinearInterpolator()
            animator2.start()
            //摇摆角度
            val animator3 =
                ObjectAnimator.ofFloat(imageView, "rotation", -10f,5f, 15f,  25f, 15f,5f, -10f)
            animator3.duration = 6000
            animator3.interpolator = DecelerateInterpolator()
            animator3.start()
        }, 1000)
    }

    fun hengxiangyidoong(image:View){
        val translationX = ObjectAnimator.ofFloat(image, View.TRANSLATION_X, -200f, widthPixels.toFloat())
        translationX.duration = 10000 // 设置动画持续时间（毫秒）
        translationX.interpolator = LinearInterpolator() // 设置线性插值器，使动画匀速运动
        // 创建动画集合，将平移动画加入其中
        val animatorSet = AnimatorSet()
        animatorSet.play(translationX)
        animatorSet.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
                // 动画开始时的操作
            }
            override fun onAnimationEnd(animation: Animator) {
                // 动画结束时的操作
                image.translationX = 0f // 重置视图的位置，以便下一次动画
                animatorSet.start() // 无限循环播放动画
            }
            override fun onAnimationCancel(animation: Animator) {}
            override fun onAnimationRepeat(animation: Animator) {}
        })

        // 启动动画
        animatorSet.start()
    }


    private fun startFish() {
        dataBinding.fish.setVisibility(View.VISIBLE)
    }

    private fun startPP() {
        dataBinding.pp.setVisibility(View.VISIBLE)

    }



    /**
     * Gif播放完毕回调
     */
    interface GifListener {
        fun gifPlayComplete()
    }
    //播放一次后，随机等待
    fun loadOneTimeGif(
        context: Context,
        model: Any,
        imageView: ImageView,
        gifListener: GifListener?
    ) {
        val requestOptions = RequestOptions()
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .skipMemoryCache(true)

        Glide.with(context)
            .asGif()
            .apply(requestOptions)
            .load(model)
            .into(object : ViewTarget<ImageView, GifDrawable>(imageView) {
                override fun onResourceReady(
                    resource: GifDrawable,
                    transition: Transition<in GifDrawable>?
                ) {


                }
            })
    }
    override fun initData() {

    }

    override fun initIntent() {

    }
    
}